package com.xhtech.base.ext.vm

import androidx.lifecycle.liveData
import com.yxh.lib_base.util.LogUtils
import com.xhtech.base.network.config.ApiResponse
import com.xhtech.base.network.config.ResultApi
import com.yxh.lib_base.base.viewmodel.BaseViewModel
import com.yxh.lib_base.base.viewmodel.dismissLoading
import com.yxh.lib_base.base.viewmodel.showLoading
import com.yxh.lib_base.network.BaseResponse
import com.yxh.lib_base.network.ExceptionHandle

/**
 * @author yuanxh
 * @date :2023/6/21 21:11
 * @description:
 */
fun <T, R : BaseResponse<T>> BaseViewModel.requestNetWorkLiveData(
    block: suspend () -> ApiResponse<T>,
    isShowLoading: Boolean = false,
    loadingMessage: String = "请求网络中...",
) = liveData {
    runCatching {
        if (isShowLoading) showLoading(loadingMessage)
        //请求体
        block()
    }.onSuccess {
        //网络请求成功 关闭弹窗
        dismissLoading()
        emit(it)
    }.onFailure {
        //网络请求异常 关闭弹窗
        dismissLoading()
        //打印错误消息
        LogUtils.e(it)
        //失败回调
        val error = ExceptionHandle.handleException(it)
        emit(ApiResponse<T?>(error.errCode, error.errorMsg, null))
    }
}

fun <T, R : BaseResponse<T>> BaseViewModel.requestApi2LiveData(
    block: suspend () -> ApiResponse<T>,
    isShowLoading: Boolean = false,
    loadingMessage: String = "请求网络中...",
) = liveData {
    runCatching {
        if (isShowLoading) showLoading(loadingMessage)
        //请求体
        block()
    }.onSuccess {
        //网络请求成功 关闭弹窗
        dismissLoading()
        emit(ResultApi(it.getCode(),it.getMsg(),it.getData()))
    }.onFailure {
        //网络请求异常 关闭弹窗
        dismissLoading()
        //打印错误消息
        LogUtils.e(it)
        //失败回调
        val error = ExceptionHandle.handleException(it)
        emit(ResultApi(error.errCode, error.errorMsg, null))
    }
}

